package com.wechat.mp.controller;

import com.alibaba.fastjson.JSON;
import com.wechat.mp.common.RetEntry;
import com.wechat.mp.config.WebchatConfig;
import com.wechat.mp.config.WxMpProperties;
import com.wechat.mp.entity.UserInfo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Slf4j
@Controller
@AllArgsConstructor
@RequestMapping("/vote")
public class WxVoteController {
    private final WxMpService wxService;
    @Autowired
    WxMpProperties wxMpProperties;

    /**
     * 业主信息确认
     * @return
     */
    @RequestMapping("/infoConfirm")
    public String infoConfirm(String code, Model model) {
        log.info("微信用户code",code);
        //通过code换取access_token的票据每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期。
        try {
            if(StringUtils.isNotEmpty(code)){
                //根据code获取用户tocken
                WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxService.oauth2getAccessToken(code);
                log.info("通过code获取tocken",wxMpOAuth2AccessToken.getAccessToken());
                //通过access_token拉取用户信息
                WxMpUser wxMpUser = wxService.oauth2getUserInfo(wxMpOAuth2AccessToken, "");
                log.info("access_token拉取用户信息","用户名："+wxMpUser.getNickname());
                model.addAttribute("nickname",wxMpUser.getNickname());
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "infoConfirm";
    }

    @RequestMapping("/index")
    public String success(String code, Model model) {
        return "index";
    }

    /**
     * 业主信息保存
     * @return
     */
    @ResponseBody
    @RequestMapping("/saveuserinfo")
    public String saveuserinfo(UserInfo user) {
        log.info("user",user);
        return "成功";
    }

    /**
     * 多文件上传
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/uploadUserpicMulti")
    public RetEntry uploadUserpicMulti(HttpServletRequest request) throws Exception{
        RetEntry retEntry = new RetEntry(RetEntry.CODE_ERROR, "数据返回为空");
        MultipartHttpServletRequest muRequest =(MultipartHttpServletRequest) request;
        List<MultipartFile> files = muRequest.getFiles("file[]");

        File targetFile=null;
        String msg="";//返回存储路径
        List imgList=new ArrayList();
        if (files!=null && files.size()>0) {
            for (int i = 0; i < files.size(); i++) {
                String fileName=files.get(i).getOriginalFilename();//获取文件名加后缀
                uploadfile(request, files.get(i), imgList, fileName);
            }
            retEntry.setRetCode(RetEntry.CODE_SUCC);
            retEntry.setRetMsg("批量上传成功");
            retEntry.addData("imgList",imgList);
        }
        return retEntry;
    }

    /**
     * 单文件上传
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/uploadUserpic")
    public RetEntry uploadUserpic(HttpServletRequest request) throws Exception{
        RetEntry retEntry = new RetEntry(RetEntry.CODE_ERROR, "数据返回为空");
        MultipartHttpServletRequest muRequest =(MultipartHttpServletRequest) request;
        MultipartFile file = muRequest.getFile("file");

        File targetFile=null;
        String msg="";//返回存储路径
        List imgList=new ArrayList();
        if (file!=null) {
            String fileName=file.getOriginalFilename();//获取文件名加后缀
            uploadfile(request, file, imgList, fileName);
            retEntry.setRetCode(RetEntry.CODE_SUCC);
            retEntry.setRetMsg("上传成功");
            retEntry.addData("imgList",imgList);
        }

        return retEntry;
    }

    /**
     * 文件上传通用方法
     * @param request
     * @param file
     * @param imgList
     * @param fileName
     */
    private void uploadfile(HttpServletRequest request, MultipartFile file, List imgList, String fileName) {
        File targetFile;
        String msg;
        if (fileName != null && fileName != "") {
            String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/file/";//存储路径
            String path = WebchatConfig.getProfile(); //文件存储位置
            log.info("文件存储位置:" + path);
            String fileSuff = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
            fileName = new Date().getTime() + "_" + new Random().nextInt(1000) + fileSuff;//新的文件名
            log.info("新的文件名:" + fileName);
            String fileAdd = DateUtils.formatDate(new Date(), "yyyyMMdd");
            File file1 = new File(path + "//" + fileAdd);
            //如果文件夹不存在则创建
            if (!file1.exists() && !file1.isDirectory()) {
                file1.mkdirs();
            }
            targetFile = new File(file1, fileName);
            try {
                file.transferTo(targetFile);
                msg = returnUrl + fileAdd + "/" + fileName;
                log.info("文件名请求路径:" + msg);
                imgList.add(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
